#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
请求速率限制器
快代理限制：并发请求量10次/s
"""
import time
import threading
import logging
from collections import deque

__author__ = 'myh '
__date__ = '2025/11/5 '

# 配置日志记录器（可选，用于调试）
logger = logging.getLogger(__name__)


class RequestRateLimiter:
    """
    请求速率限制器，确保不超过快代理的10次/秒限制
    使用令牌桶算法
    """
    _instance = None
    _lock = threading.Lock()
    
    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super(RequestRateLimiter, cls).__new__(cls)
                    cls._instance._initialized = False
        return cls._instance
    
    def __init__(self):
        if self._initialized:
            return
        self._initialized = True
        # 快代理限制：10次/秒，保守设置为1.0秒间隔（约1次/秒），避免代理异常
        self.min_interval = 1.0  # 每次请求最小间隔（秒）
        self.last_request_time = 0
        self.request_times = deque()  # 记录最近10次请求的时间
        self.lock = threading.Lock()
    
    def wait_if_needed(self):
        """
        如果需要，等待直到可以发送下一个请求
        """
        with self.lock:
            current_time = time.time()
            
            # 清理超过1秒的旧记录
            while self.request_times and current_time - self.request_times[0] > 1.0:
                self.request_times.popleft()
            
            # 如果已经有2个请求在1秒内，需要等待（非常保守的限制，避免代理压力过大）
            if len(self.request_times) >= 2:
                # 等待直到最早的请求超过1秒
                wait_time = self.request_times[0] + 1.0 - current_time
                if wait_time > 0:
                    logger.info(f"限流器: 1秒内已有{len(self.request_times)}个请求，等待 {wait_time:.3f}秒")
                    time.sleep(wait_time)
                    current_time = time.time()
            
            # 确保最小间隔
            time_since_last = current_time - self.last_request_time
            if time_since_last < self.min_interval:
                wait_duration = self.min_interval - time_since_last
                logger.info(f"限流器生效: 距离上次请求 {time_since_last:.3f}秒，等待 {wait_duration:.3f}秒 后发送请求")
                time.sleep(wait_duration)
                current_time = time.time()
            
            # 记录这次请求
            self.last_request_time = current_time
            self.request_times.append(current_time)
            
            # 确保队列不超过10个
            while len(self.request_times) > 10:
                self.request_times.popleft()


# 全局实例
_rate_limiter = None

def get_rate_limiter():
    """获取全局速率限制器实例"""
    global _rate_limiter
    if _rate_limiter is None:
        _rate_limiter = RequestRateLimiter()
    return _rate_limiter


def wait_for_request():
    """等待直到可以发送下一个请求"""
    get_rate_limiter().wait_if_needed()

